home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 2000 July / macformat-092.iso / Dreamweaver 3 / Configuration / Commands / Tabular Data.js < prev   
Encoding:
Text File  |  1999-12-01  |  12.9 KB  |  434 lines

  1. // Copyright 1999 Macromedia, Inc. All rights reserved
  2.  
  3. //---------------   GLOBAL VARIABLES   ---------------
  4.  
  5. var helpDoc = MM.HELP_objTabularData;
  6.  
  7. //---------------     API FUNCTIONS    ---------------
  8.  
  9. function commandButtons(){
  10.    return new Array(BTN_OK,         "createTableStr()",
  11.                     BTN_Cancel,     "window.close()",
  12.                     BTN_Help,       "displayHelp()" );
  13. }
  14.  
  15. //---------------    LOCAL FUNCTIONS   ---------------
  16.  
  17. function setTableFileToImport() {
  18.   var fName = dw.browseForFileURL('open','', false, true);
  19.   if (fName) {
  20.     document.forms[0].DataFile.value =  fName;
  21.     setDelimiter(fName);
  22.   }
  23. }
  24.  
  25. //function:setDelimiter
  26. //description: after choosing a file, set delimiter select menu
  27. //based on file type, e.g.: set it to Comma if a *.csv file is chosen
  28.  
  29. function setDelimiter(fileName){
  30.    var selDelimiter = document.forms[0].Delimiter;
  31.    var extension = fileName.substring(  fileName.indexOf(".")  );
  32.    
  33.    if (extension==".csv")   selDelimiter.selectedIndex = 1; //comma
  34.    if (extension==".xls")   alert( ERROR_Unsupported_Format + ERROR_Supported_Formats);
  35.    //if we support more formats in the future
  36.    //such as space-delimited (.csv), more checks may be added here
  37. }
  38.  
  39. //function:getDelimiter
  40. //description: returns user-chosen delimiter based on form parameters
  41.  
  42. function getDelimiter(theForm){
  43.    var retVal;
  44.    var selInd = theForm.Delimiter.selectedIndex;
  45.    
  46.    switch (selInd){
  47.       case 0:
  48.          retVal = "\t";   
  49.          break;
  50.       case 1:
  51.          retVal = ",";
  52.          break;
  53.       case 2:
  54.          retVal = ";";
  55.          break;
  56.       case 3:
  57.          retVal = ":";
  58.          break;
  59.       case 4:
  60.          retVal = theForm.CustomDelimiter.value;
  61.          break;
  62.    }
  63.    return retVal;
  64. }
  65.  
  66. //function: getNewLineChar
  67. //description: returns newline character
  68.  
  69. function getNewLineChar(dataStr){
  70.    var retVal;
  71.    
  72.    if (  dataStr.search("\r\n")!= -1)
  73.       retVal = "\r\n";
  74.    else if (  dataStr.search("\n")!= -1)
  75.       retVal="\n";
  76.    else
  77.       retVal="\r";
  78.       
  79.    return retVal;
  80.    
  81. }
  82.  
  83.  
  84. //function: getFormatTags
  85. //description: returns a two-item array representing opening and closing 
  86. //format tags to be used in the first row based on FormatTopRow form parameter
  87.  
  88. function getFormatTags(theForm){
  89.    var retVal = new Array("","");
  90.    var selInd = theForm.FormatTopRow.selectedIndex;
  91.    
  92.    switch (selInd){
  93.       case 1:
  94.          retVal[0] = "<b>";
  95.          retVal[1] = "</b>";
  96.          break;
  97.       case 2:
  98.          retVal[0] = "<i>";
  99.          retVal[1] = "</i>";
  100.          break;
  101.       case 3:
  102.          retVal[0] = "<b><i>";
  103.          retVal[1] = "</i></b>";
  104.          break;  
  105.    }
  106.    return retVal;
  107. }
  108.  
  109.  
  110. //function: createTableStr
  111. //description: creates the html table based on the form parameters
  112.  
  113. function createTableStr(){
  114.    var theForm = document.forms[0];
  115.    var delimiter = getDelimiter(theForm);
  116.    if (!delimiter){
  117.       alert(ERROR_No_Delimiter);
  118.       return;
  119.    }
  120.    if (delimiter.length>1){
  121.       alert(ERROR_Incorrect_Delimiter);
  122.       return;
  123.    }
  124.    var bAutoWidth = theForm.Width[0].checked;
  125.    if (!bAutoWidth){
  126.       var unitChoice = (theForm.WidthUnit.selectedIndex==0)?'%':'';
  127.       var width = theForm.WidthValue.value + unitChoice;
  128.    }
  129.    var cellSpacing = theForm.CellSpacing.value;
  130.    var cellPadding = theForm.CellPadding.value;
  131.    var border = theForm.Border.value;
  132.    var formatFirstRowArr = getFormatTags(theForm);   
  133.    var openTag = createOpenTableTag(width,border,cellSpacing,cellPadding);
  134.    
  135.    var dataFile = theForm.DataFile.value;
  136.    if ( dataFile && dataFile.substring(dataFile.lastIndexOf(".")) == ".xls"){
  137.       alert(ERROR_Unsupported_Format + ERROR_Supported_Formats);
  138.       return;
  139.    }
  140.    
  141.    var tableFileURL = getFullPath(dataFile);
  142.    if (  !verifyFilePath(tableFileURL)  )
  143.       return;
  144.       
  145.   MM.setBusyCursor();
  146.   var dataStr = DWfile.read(tableFileURL);
  147.   var newline = getNewLineChar(dataStr);
  148.   
  149.   dw.getDocumentDOM().insertHTML( openTag + createTableBody(dataStr,delimiter,newline,formatFirstRowArr) + 
  150.               "</TABLE>" );
  151.  
  152.   MM.clearBusyCursor();
  153.  
  154.   window.close();
  155.   
  156. }
  157.  
  158. //function: verifyFilePath
  159. //description: verify that file path is not null and is correct
  160. //and alert correct error message in each case
  161. //returns: true if valid, false if invalid
  162.  
  163. function verifyFilePath(fileURL){
  164.    retVal = true;
  165.    
  166.    //if no file path or incorrect file path, alert error message
  167.    if ( !fileURL ){
  168.       alert(ERROR_No_File)
  169.       retVal=false;
  170.    } else if (  !DWfile.exists( fileURL)  ){
  171.       alert(ERROR_Incorrect_File_Path)
  172.       retVal=false;
  173.    }
  174.    return retVal;
  175. }
  176.  
  177. //function: createOpenTableTag
  178. //description: creates an open table tag based on argument values
  179.  
  180.  function createOpenTableTag(width,border,cellSpacing,cellPadding){
  181.     var openTag = '<TABLE';
  182.     
  183.     if (width)         openTag +=' width="' + width + '"';
  184.     if (border)        openTag +=' border="' + border + '"';
  185.     if (cellSpacing)   openTag +=' cellspacing="' + cellSpacing + '"';
  186.     if (cellPadding)   openTag +=' cellpadding="' + cellPadding + '"';
  187.     
  188.     return openTag + '>';
  189.  
  190.  }
  191.  
  192. //function: getTableCells
  193. //description:returns an array of the table cell data.
  194. //Parses row data to take into account cases where
  195. //the delimiter is included in the cell.
  196. //For example, if the delimiter is a comma
  197. //ensures we don't divide the data at the comma in "Doe, Jane".
  198. //Note:Excel places double quotes around data with reserved characters
  199. //and surrounds double quotes with quotes.
  200. //Examples:
  201. //Excel (.xls file)  ->  Delimited file
  202. //Doe,Jane    ->       "Doe,Jane"
  203. //My name is "Jane" ->  "My name is ""Jane"""
  204. //
  205. //Arguments:
  206. //rowData - text string from original file that represents
  207. //one row of data
  208. //delimiter - character used to separate entries
  209.  
  210.  
  211.  function getTableCells(rowData,delimiter){
  212.     var retArr = new Array();
  213.     var startingOffset = 0;
  214.     var endingOffset = 0;
  215.     var cellData="";
  216.     var qualifier='"'; //qualifer is double quotes
  217.     var dataLen=0;
  218.     var rowDataLen = 0;
  219.     var qualifierCount = 0;
  220.     var i,j;
  221.     var lastInd;
  222.     
  223.    // Optimization
  224.    //if tab-delimited, just split data at tabs and return.
  225.    if (delimiter == "\t") {
  226.       retArr = rowData.split(delimiter);
  227.       return retArr;
  228.    }
  229.    
  230.     
  231.     //When we encounter a delimiter, we want to determine if the
  232.     //the delimiter is separating data: e.g: a,b,c, or
  233.     //if it included in the cell data: "Doe, Jane"
  234.     //To accomplish this goal, we count the number of double quotes
  235.     //between the beginning of the data and the delimiter character 
  236.     //that we find.
  237.     //If this number is even, we have completed getting the cell data.
  238.     //If it is odd, the cell data is not complete so we step
  239.     //through until reaching the next delimiter and repeat the 
  240.     //double-quote test.
  241.     
  242.     rowDataLen = rowData.length;
  243.     lastInd = rowDataLen - 1;
  244.     for (i=0;i<rowDataLen;i++){
  245.  
  246.        if (  rowData.charAt(i)==delimiter || i == lastInd ){
  247.           endingOffset = i;
  248.           if (  i!=lastInd || rowData.charAt(lastInd) == delimiter  ){
  249.              cellData = rowData.substring(startingOffset,endingOffset);
  250.           } else {
  251.              cellData = rowData.substring(startingOffset);
  252.           }       
  253.           //The way we are dividing the data, the delimiter character
  254.           //is the first character in all but the first data string
  255.           //We want to delete it.
  256.           if ( cellData[0] == delimiter ){
  257.              if (  cellData.charAt(1)  )
  258.                 cellData = cellData.substring(1);
  259.              else
  260.                 cellData = "";
  261.           }
  262.         
  263.           //Go through the cell data and count the number of double quotes
  264.           //I've assigned the double quotes to a qualifier variable
  265.           //to make it easy to allow custom qualifiers in future versions
  266.           if (cellData){
  267.              dataLen = cellData.length;
  268.              for (j=0;j<dataLen;j++){
  269.                 if (cellData.charAt(j) == qualifier)
  270.                    qualifierCount++;
  271.              }
  272.           }
  273.  
  274.           //if this is the complete cell data, add it to the return array
  275.           //and reset start offset to the end of the cell data we have
  276.           //just processed
  277.           if (qualifierCount%2==0){ 
  278.              retArr[retArr.length] = cellData;  
  279.              startingOffset = endingOffset; 
  280.           } 
  281.        }
  282.        qualifierCount=0;
  283.     }
  284.     //if far right cell is blank, add last cell to return array:
  285.     if (  rowData.charAt( lastInd )==delimiter  )
  286.        retArr[retArr.length] = "";
  287.  
  288.    return retArr; // Note: optimization return at beginning of function.
  289. }
  290.  
  291.  
  292.  //function: createTable
  293.  //description: creates the body of the table based on the contents of the
  294.  //tabular data file. Parses contents of tabular data file.
  295.  
  296.  function createTableBody(dataStr,delimiter,newline,formatFirstRowArr){
  297.    var tableHTML = new Array();
  298.    var tableRows = dataStr.split(newline);
  299.    var firstRow = tableRows[0];
  300.    var tableCells;
  301.    var nCells;
  302.    var i,j,k;
  303.    var lastCharOfNewLine = newline.charAt(newline.length-1);
  304.    var nRows = ( dataStr.charAt(dataStr.length-1)!=lastCharOfNewLine  )?
  305.                tableRows.length:tableRows.length-1;
  306.    var openFormat = formatFirstRowArr[0];
  307.    var closeFormat = formatFirstRowArr[1];
  308.    var cellContents = "";
  309.    
  310.    // Start the first row.
  311.    tableHTML[tableHTML.length] = '<TR>';
  312.  
  313.    //first row is processed separately because it may be formatted (e.g: bold)
  314.    tableCells = getTableCells(firstRow,delimiter);
  315.    
  316.    nCells = tableCells.length;
  317.    for (i=0;i<nCells;i++){
  318.       cellContents = parseData(tableCells[i]);
  319.       if (cellContents) {
  320.          tableHTML[tableHTML.length] = "<TD>" + openFormat + cellContents + closeFormat + "</TD>";
  321.       } else {
  322.          tableHTML[tableHTML.length] = "<TD> </TD>";
  323.       }
  324.    }
  325.    tableHTML[tableHTML.length] = "</TR>";
  326.    
  327.    for (i=1;i<nRows;i++){
  328.       tableHTML[tableHTML.length] = "<TR>";
  329.        tableCells = getTableCells(tableRows[i],delimiter);
  330.      
  331.      var cellContent="";
  332.      for (j=0;j<nCells;j++){
  333.          cellContents = parseData(tableCells[j]);
  334.          if (cellContents) {
  335.             tableHTML[tableHTML.length] = "<TD>" + cellContents + "</TD>";
  336.          } else {
  337.             tableHTML[tableHTML.length] = "<TD> </TD>";
  338.          }
  339.      }
  340.      tableHTML[tableHTML.length] = "</TR>";
  341.    }
  342.    
  343.    tableHTML[tableHTML.length] = "</TABLE>";
  344.    
  345.    return tableHTML.join('');
  346. }
  347.  
  348. //function: parseData
  349. //description: Excel exports tabular data with extra quotes to qualify
  350. //delimiiters. For instance, in a comma-delimited file, an entry of
  351. //Doe, Jane would be exported as "Doe, Jane". Also, Excel surrounds all
  352. //double quotes with quotes: An excel entry of "Boo" is exported as ""Boo"".
  353. //This function "cleans up" the data so that it can be displayed cleanly
  354. //in an html table. ( In other words, we want to see Doe, Jane in the html
  355. //table, not "Doe, Jane" )
  356.  
  357. function parseData(dataStr) {
  358.   //if dataStr is empty, return:
  359.   if (!dataStr) return '';
  360.   var qualifier = '"'  //qualifier equals double quotes
  361.   var strLen;
  362.   
  363.   if (dataStr.charAt(0) == qualifier && dataStr.charAt(dataStr.length-1) == qualifier){
  364.      dataStr = dataStr.substring(1,dataStr.length-1);
  365.   }
  366.   strLen = dataStr.length - 1; // Searching for pairs, don't search last char.
  367.   
  368.   for (var counter=0; counter < strLen; counter++) {
  369.     //Excel surrounds all double quotes in quotes when exporting to delimited file
  370.     //Following if clause removes them for a clean display
  371.     
  372.     if (dataStr.charAt(counter) == qualifier && dataStr.charAt(counter+1) == qualifier) {
  373.       if (counter==0)
  374.         dataStr = dataStr.substring(1);
  375.       else
  376.         dataStr = dataStr.substring(0,counter) + dataStr.substring(counter+1);
  377.       continue;
  378.     }
  379.   }
  380.  
  381.   return dataStr;
  382. }
  383.  
  384. //function: toggleCustomField
  385. //description: if Other is chosen in the Delimiter Type select list,
  386. //this function makes a text entry field dynamically appear. Also
  387. //hides it if Other is not chosen
  388.  
  389. function toggleCustomField(optionText){
  390.    // Ignore OptionText because it is localized.
  391.    var theForm = document.forms[0];
  392.    // The "other" option is always last, check if the last option is selected.
  393.    if (theForm.Delimiter.options.length==(theForm.Delimiter.selectedIndex+1)){
  394.       findObject("DelimiterSpan").innerHTML = '<input type="text" maxlength="1" name="CustomDelimiter" size="7">';
  395.    } else {
  396.       findObject("DelimiterSpan").innerHTML = '';
  397.    }
  398. }
  399.  
  400.  
  401. //function: innitializeUI
  402. //description: loads the select menus with localized text strings
  403. //and performs other tasks relating to initializing the UI
  404.  
  405. function initializeUI(){
  406.  
  407.    var theForm = document.forms[0];
  408.  
  409.    //If "other" is chosen in the delimiter type select widget, a
  410.    //text field is dynamically added allowing the user to enter a
  411.    //custom delimiter.
  412.    //If this happens, the height of the table cell is re-calculated
  413.    //(which is visually jarring) unless we include a text field in the 
  414.    //table row when loading the file. the line below hides this field:
  415.    findObject("DelimiterSpan").innerHTML="";
  416.    
  417.    //put focus in data file name field
  418.    theForm.DataFile.focus();
  419.    
  420.    //place localized text strings in select widgets
  421.    //variable name note: variable names preceded by sel
  422.    //indicate a select widget object
  423.     
  424.    var selDelimiter = theForm.Delimiter;
  425.    var selFormatTopRow = theForm.FormatTopRow;
  426.    var selWidthUnit = theForm.WidthUnit;
  427.     
  428.    loadSelectList(selDelimiter,OPTIONS_Delimiters);
  429.    loadSelectList(selFormatTopRow,OPTIONS_Formatting);
  430.    loadSelectList(selWidthUnit,OPTIONS_Units);
  431.    
  432. }
  433.  
  434.